package yf.platform.loader;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.c3p0.C3p0Plugin;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Map;

public class Loader {

    private static final Logger logger = LogManager.getLogger(Loader.class);
    //确保为单例模式

    private static Loader _instance = null;

    private Loader(){}

    public static synchronized Loader me(){
        if(_instance == null){
            _instance = new Loader();
        }
        return _instance;
    }

    //使用到的所有的数据源
    C3p0Plugin db;
    //数据操作的jfinal插件
    ActiveRecordPlugin arp;


    //加载成功的标示位
    private boolean _isLoaded = false;

    //数据库链接地址
    private String _dbHost = "";

    private String _dbUser = "";

    //数据库的名字
    private String _dbName = "";

    //数据库的密码
    private String _dbPass = "";

    //开发模式，DEV、STAGING、PRODUCT
    private String _devMode = "DEV";

    public String getDevMode(){
        return _devMode;
    }

    //初始化函数
    public final boolean init(){

        //加载成功之后，避免多次加载
        if(_isLoaded) return true;

        //加载app.config文件
        PropKit.use("app.config");
        //开发模式
        //优先加载环境变量中的配置信息
        Map map = System.getenv();

        _devMode = map.getOrDefault("DEV_MODE",PropKit.get("devMode")).toString();

        logger.info("_devMode:" + _devMode);

        String commonStr = PropKit.get(_devMode);

        JSONObject commonJson = JSON.parseObject(commonStr);


        //加载开发模式下的配置
        _dbUser = commonJson.getString("user");
        _dbPass = commonJson.getString("pass");
        _dbHost = commonJson.getString("host");
        _dbName = commonJson.getString("dbname");

        try {

            //创建数据源链接
            db = new C3p0Plugin("jdbc:mysql://" +
                    _dbHost + "/" + _dbName +"?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull",
                    _dbUser,
                    _dbPass);
            db.setMaxPoolSize(30);
            db.setMinPoolSize(1);
            db.setInitialPoolSize(1);
            //启动数据源
            db.start();
            //创建数据连接的插件
            arp = new ActiveRecordPlugin(db);
            arp.setShowSql(true);
            //启动插件
            arp.start();
        }catch(Exception hex){
            logger.error(hex.getMessage());
            return false;
        }
        logger.info("loader init ok~~");
        _isLoaded = true;
        return true;
    }


}
